const app = angular.module("myApp",['ui.bootstrap']);

app.controller("reportController",['$scope','$compile','$sce',function($scope,$compile,$sce){
    $scope.toJSON = function (val) {
        return toJSON(val);
    };
    let request = getRequest();
    $scope.faultId = request["faultId"];
    // $scope.featureIds = JSON.parse(request["featureIds"]);
    console.info(request["matchedNodes"]);
    $scope.matchedNodes = JSON.parse(request["matchedNodes"]);
    $scope.timestamp = new Date(parseInt(request["timestamp"]));

    $scope.sequence = '001232016072010010121001';
    $scope.reasons = [];

    let queryUrl = `start n=node(${$scope.faultId}) match (n)-[*]->(p) return n,p`;
    $scope.faultUrl = $sce.trustAsResourceUrl(`../browser/NeoEmbed.html?query=${encodeURIComponent(queryUrl).replace(/=/g,'%3d')}`);

    Graph.loadGraph($scope.faultId,g=>{
        $scope.graph = g;
        let nodesList = [... g.nodes.values()];
        for(let nd of nodesList){
            if($scope.matchedNodes.some(nid=>nid==nd.id)){
                nd.isMatched = true;
            }
        }
        $scope.fault = nodesList.filter(node=>node.$type=="Fault")[0];
        $scope.features = nodesList.filter(node=>node.$type=='Feature').sort((a,b)=>a>b);
        $scope.features.forEach((f,index)=>{
            ComponentNode.loadComponentsFrom(f.id,
                (components)=>{
                    $scope.features[index].components=components;
                    $scope.$apply();
                }
            );
        });
        let matchedOutIds = $scope.features.filter(f=>f.isMatched).map(f=>f.outId).filter(id=>id!=0);
        console.info(matchedOutIds);
        $scope.reasons = nodesList.filter(node=>node.$type=='Reason').sort((a,b)=>a>b);
        $scope.reasons.filter(r=>matchedOutIds.some(id=>id==r.outId)).forEach(r=>r.isMatched=true);
        $scope.$apply();
    });

    $scope.getNow=function () {
        return $scope.timestamp;
    };

}]);

const toJSON = function (obj) {
    let cache = [];
    return JSON.stringify(obj, function(key, value) {
        if (typeof value === 'object' && value !== null) {
            if (cache.indexOf(value) !== -1) {
                // Circular reference found, discard key
                return;
            }
            // Store value in our collection
            cache.push(value);
        }
        return value;
    });
};

function getRequest() {
    let url = location.search; //获取url中"?"符后的字串
    let theRequest = {};
    if (url.indexOf("?") !== -1) {
        let str = url.substr(1);
        let strs = str.split("&");
        for(let i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}